package cn.clq.ymcc.web.controller;

import cn.clq.ymcc.domain.PayOrder;
import cn.clq.ymcc.dto.AlipayNotifyDto;
import cn.clq.ymcc.dto.PayApplyDto;
import cn.clq.ymcc.result.JSONResult;
import cn.clq.ymcc.service.IPayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author clqlongbao
 * @version 1.0
 * @description: 前端发起支付请求的接口
 * @date 2022/8/1 12:27
 */
@RestController
@RequestMapping("/pay")
public class PayApplyController {
    @Autowired
    private IPayOrderService payOrderService;

    /**
     * @description: 根据订单号查询支付单是否已经存在了(消费者是否已经消费)
     * @param: orderNo
     * @return: cn.clq.ymcc.result.JSONResult
     * @author clqlongbao
     * @date: 2022/8/1 12:32
     */
    @GetMapping("/checkPayOrder/{orderNo}")
    public JSONResult checkPayOrder(@PathVariable("orderNo") String orderNo){
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
        System.out.println("前端轮询，支付单为："+payOrder);
        // 支付单已经存在那么就返回success  支付单没有存在就返回false
        return payOrder == null? JSONResult.error() : JSONResult.success();
    }

    /**
     * @description:  发起支付请求，返回登陆支付宝的form表单字符串
     * @param: dto
     * @return: cn.clq.ymcc.result.JSONResult
     * @author clqlongbao
     * @date: 2022/8/1 22:18
     */
    @PostMapping("/apply")
    public JSONResult apply(@RequestBody PayApplyDto dto){
        // 向支付宝发起申请,返回from表单
        String formStr= payOrderService.apply(dto);
        return JSONResult.success(formStr);
    }


    /**
     * @description:  支付宝的异步回调接口
     * @param: dto
     * @return: success 或者别的字符串
     *         如果返回success给支付宝，那么支付宝不再通知你了
     *         如果返回的是非success，那么支付宝会一直尝试通知您，直到8次通知
     * @author clqlongbao
     * @date: 2022/8/3 23:07
     */

    @PostMapping("/alipay/notify")
    //这里不能用requestbody接收参数，支付宝已经帮我们封装好了
    public String notify(AlipayNotifyDto dto){
        System.out.println("支付宝异步回调开始");
        try {
            return payOrderService.notify(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return "Fail";
        }
    }
}
